﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Newtonsoft.Json;

namespace DidaManager.Models
{
    /// <summary>
    /// MQTT配置项数据模型
    /// </summary>
    public class MqttConfigItem
    {
        /// <summary>
        /// 配置项名称
        /// </summary>
        [JsonProperty("name")]
        public string Name { get; set; } = string.Empty;
        
        /// <summary>
        /// 配置项ID
        /// </summary>
        [JsonProperty("id")]
        public int Id { get; set; }
    }

    /// <summary>
    /// MQTT UI配置数据模型
    /// </summary>
    public class MqttUIConfigData
    {
        /// <summary>
        /// 主题列表
        /// </summary>
        [JsonProperty("Topic")]
        public List<MqttConfigItem> Topic { get; set; } = new List<MqttConfigItem>();
        
        /// <summary>
        /// 负载列表
        /// </summary>
        [JsonProperty("Payload")]
        public List<MqttConfigItem> Payload { get; set; } = new List<MqttConfigItem>();
        
        /// <summary>
        /// 网卡列表
        /// </summary>
        [JsonProperty("NetworkCard")]
        public List<MqttConfigItem> NetworkCard { get; set; } = new List<MqttConfigItem>();
        
        /// <summary>
        /// 服务器类型列表
        /// </summary>
        [JsonProperty("ServerType")]
        public List<MqttConfigItem> ServerType { get; set; } = new List<MqttConfigItem>();

        /// <summary>
        /// 阿里云区域类型列表
        /// </summary>
        [JsonProperty("AliCloudType")]
        public List<MqttConfigItem> AliCloudType { get; set; } = new List<MqttConfigItem>();
    }

    /// <summary>
    /// MQTT UI配置管理器
    /// </summary>
    public class MqttUIConfig
    {
        /// <summary>
        /// 全局存储的MQTT配置数据
        /// </summary>
        private static MqttUIConfigData? _mqttConfigData;
        
        /// <summary>
        /// 是否已加载数据
        /// </summary>
        private static bool _isDataLoaded = false;
        
        /// <summary>
        /// 配置文件路径
        /// </summary>
        private static string _configFilePath = string.Empty;

        /// <summary>
        /// 获取是否已加载数据
        /// </summary>
        public static bool IsDataLoaded => _isDataLoaded;

        /// <summary>
        /// 获取当前配置文件路径
        /// </summary>
        public static string ConfigFilePath => _configFilePath;

        /// <summary>
        /// 获取所有MQTT配置数据（只读）
        /// </summary>
        public static MqttUIConfigData? AllConfigData => _mqttConfigData;

        /// <summary>
        /// 从JSON文件加载MQTT配置
        /// </summary>
        /// <param name="filePath">JSON文件路径</param>
        /// <returns>是否加载成功</returns>
        public static bool LoadFromJsonFile(string filePath)
        {
            try
            {
                // 检查文件是否存在
                if (!File.Exists(filePath))
                {
                    return false;
                }

                // 读取JSON文件内容
                string jsonContent = File.ReadAllText(filePath, Encoding.UTF8);
                
                // 反序列化JSON数据
                _mqttConfigData = Newtonsoft.Json.JsonConvert.DeserializeObject<MqttUIConfigData>(jsonContent);
                
                if (_mqttConfigData != null)
                {
                    _isDataLoaded = true;
                    _configFilePath = filePath;
                    return true;
                }
                
                return false;
            }
            catch
            {
                _isDataLoaded = false;
                _configFilePath = string.Empty;
                return false;
            }
        }

        /// <summary>
        /// 异步加载JSON文件
        /// </summary>
        /// <param name="filePath">JSON文件路径</param>
        /// <returns>加载任务</returns>
        public static async Task<bool> LoadFromJsonFileAsync(string filePath)
        {
            return await Task.Run(() => LoadFromJsonFile(filePath));
        }

        /// <summary>
        /// 获取Topic列表
        /// </summary>
        /// <returns>Topic列表</returns>
        public static List<MqttConfigItem> GetTopicList()
        {
            if (!_isDataLoaded || _mqttConfigData?.Topic == null)
            {
                return new List<MqttConfigItem>();
            }
            
            return _mqttConfigData.Topic.ToList();
        }

        /// <summary>
        /// 获取Topic名称列表
        /// </summary>
        /// <returns>Topic名称列表</returns>
        public static List<string> GetTopicNameList()
        {
            if (!_isDataLoaded || _mqttConfigData?.Topic == null)
            {
                return new List<string>();
            }
            
            return _mqttConfigData.Topic.Select(t => t.Name).ToList();
        }

        /// <summary>
        /// 获取Topic ID列表
        /// </summary>
        /// <returns>Topic ID列表</returns>
        public static List<int> GetTopicIdList()
        {
            if (!_isDataLoaded || _mqttConfigData?.Topic == null)
            {
                return new List<int>();
            }
            
            return _mqttConfigData.Topic.Select(t => t.Id).ToList();
        }

        /// <summary>
        /// 获取Payload列表
        /// </summary>
        /// <returns>Payload列表</returns>
        public static List<MqttConfigItem> GetPayloadList()
        {
            if (!_isDataLoaded || _mqttConfigData?.Payload == null)
            {
                return new List<MqttConfigItem>();
            }
            
            return _mqttConfigData.Payload.ToList();
        }

        /// <summary>
        /// 获取Payload名称列表
        /// </summary>
        /// <returns>Payload名称列表</returns>
        public static List<string> GetPayloadNameList()
        {
            if (!_isDataLoaded || _mqttConfigData?.Payload == null)
            {
                return new List<string>();
            }
            
            return _mqttConfigData.Payload.Select(p => p.Name).ToList();
        }

        /// <summary>
        /// 获取Payload ID列表
        /// </summary>
        /// <returns>Payload ID列表</returns>
        public static List<int> GetPayloadIdList()
        {
            if (!_isDataLoaded || _mqttConfigData?.Payload == null)
            {
                return new List<int>();
            }
            
            return _mqttConfigData.Payload.Select(p => p.Id).ToList();
        }

        /// <summary>
        /// 获取NetworkCard列表
        /// </summary>
        /// <returns>NetworkCard列表</returns>
        public static List<MqttConfigItem> GetNetworkCardList()
        {
            if (!_isDataLoaded || _mqttConfigData?.NetworkCard == null)
            {
                return new List<MqttConfigItem>();
            }
            
            return _mqttConfigData.NetworkCard.ToList();
        }

        /// <summary>
        /// 获取NetworkCard名称列表
        /// </summary>
        /// <returns>NetworkCard名称列表</returns>
        public static List<string> GetNetworkCardNameList()
        {
            if (!_isDataLoaded || _mqttConfigData?.NetworkCard == null)
            {
                return new List<string>();
            }
            
            return _mqttConfigData.NetworkCard.Select(n => n.Name).ToList();
        }

        /// <summary>
        /// 获取NetworkCard ID列表
        /// </summary>
        /// <returns>NetworkCard ID列表</returns>
        public static List<int> GetNetworkCardIdList()
        {
            if (!_isDataLoaded || _mqttConfigData?.NetworkCard == null)
            {
                return new List<int>();
            }
            
            return _mqttConfigData.NetworkCard.Select(n => n.Id).ToList();
        }

        /// <summary>
        /// 获取ServerType列表
        /// </summary>
        /// <returns>ServerType列表</returns>
        public static List<MqttConfigItem> GetServerTypeList()
        {
            if (!_isDataLoaded || _mqttConfigData?.ServerType == null)
            {
                return new List<MqttConfigItem>();
            }
            
            return _mqttConfigData.ServerType.ToList();
        }

        /// <summary>
        /// 获取ServerType名称列表
        /// </summary>
        /// <returns>ServerType名称列表</returns>
        public static List<string> GetServerTypeNameList()
        {
            if (!_isDataLoaded || _mqttConfigData?.ServerType == null)
            {
                return new List<string>();
            }
            
            return _mqttConfigData.ServerType.Select(s => s.Name).ToList();
        }

        /// <summary>
        /// 获取ServerType ID列表
        /// </summary>
        /// <returns>ServerType ID列表</returns>
        public static List<int> GetServerTypeIdList()
        {
            if (!_isDataLoaded || _mqttConfigData?.ServerType == null)
            {
                return new List<int>();
            }
            
            return _mqttConfigData.ServerType.Select(s => s.Id).ToList();
        }

        /// <summary>
        /// 获取AliCloudType列表
        /// </summary>
        /// <returns>AliCloudType列表</returns>
        public static List<MqttConfigItem> GetAliCloudTypeList()
        {
            if (!_isDataLoaded || _mqttConfigData?.AliCloudType == null)
            {
                return new List<MqttConfigItem>();
            }
            
            return _mqttConfigData.AliCloudType.ToList();
        }

        /// <summary>
        /// 获取AliCloudType名称列表
        /// </summary>
        /// <returns>AliCloudType名称列表</returns>
        public static List<string> GetAliCloudTypeNameList()
        {
            if (!_isDataLoaded || _mqttConfigData?.AliCloudType == null)
            {
                return new List<string>();
            }
            
            return _mqttConfigData.AliCloudType.Select(a => a.Name).ToList();
        }

        /// <summary>
        /// 获取AliCloudType ID列表
        /// </summary>
        /// <returns>AliCloudType ID列表</returns>
        public static List<int> GetAliCloudTypeIdList()
        {
            if (!_isDataLoaded || _mqttConfigData?.AliCloudType == null)
            {
                return new List<int>();
            }
            
            return _mqttConfigData.AliCloudType.Select(a => a.Id).ToList();
        }

        /// <summary>
        /// 根据ID获取Topic
        /// </summary>
        /// <param name="id">Topic ID</param>
        /// <returns>Topic配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetTopicById(int id)
        {
            if (!_isDataLoaded || _mqttConfigData?.Topic == null)
            {
                return null;
            }
            
            return _mqttConfigData.Topic.FirstOrDefault(t => t.Id == id);
        }

        /// <summary>
        /// 根据ID获取Payload
        /// </summary>
        /// <param name="id">Payload ID</param>
        /// <returns>Payload配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetPayloadById(int id)
        {
            if (!_isDataLoaded || _mqttConfigData?.Payload == null)
            {
                return null;
            }
            
            return _mqttConfigData.Payload.FirstOrDefault(p => p.Id == id);
        }

        /// <summary>
        /// 根据ID获取NetworkCard
        /// </summary>
        /// <param name="id">NetworkCard ID</param>
        /// <returns>NetworkCard配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetNetworkCardById(int id)
        {
            if (!_isDataLoaded || _mqttConfigData?.NetworkCard == null)
            {
                return null;
            }
            
            return _mqttConfigData.NetworkCard.FirstOrDefault(n => n.Id == id);
        }

        /// <summary>
        /// 根据ID获取ServerType
        /// </summary>
        /// <param name="id">ServerType ID</param>
        /// <returns>ServerType配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetServerTypeById(int id)
        {
            if (!_isDataLoaded || _mqttConfigData?.ServerType == null)
            {
                return null;
            }
            
            return _mqttConfigData.ServerType.FirstOrDefault(s => s.Id == id);
        }

        /// <summary>
        /// 根据名称获取Topic
        /// </summary>
        /// <param name="name">Topic名称</param>
        /// <returns>Topic配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetTopicByName(string name)
        {
            if (!_isDataLoaded || _mqttConfigData?.Topic == null)
            {
                return null;
            }
            
            return _mqttConfigData.Topic.FirstOrDefault(t => 
                string.Equals(t.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 根据名称获取Payload
        /// </summary>
        /// <param name="name">Payload名称</param>
        /// <returns>Payload配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetPayloadByName(string name)
        {
            if (!_isDataLoaded || _mqttConfigData?.Payload == null)
            {
                return null;
            }
            
            return _mqttConfigData.Payload.FirstOrDefault(p => 
                string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 根据名称获取NetworkCard
        /// </summary>
        /// <param name="name">NetworkCard名称</param>
        /// <returns>NetworkCard配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetNetworkCardByName(string name)
        {
            if (!_isDataLoaded || _mqttConfigData?.NetworkCard == null)
            {
                return null;
            }
            
            return _mqttConfigData.NetworkCard.FirstOrDefault(n => 
                string.Equals(n.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 根据名称获取ServerType
        /// </summary>
        /// <param name="name">ServerType名称</param>
        /// <returns>ServerType配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetServerTypeByName(string name)
        {
            if (!_isDataLoaded || _mqttConfigData?.ServerType == null)
            {
                return null;
            }
            
            return _mqttConfigData.ServerType.FirstOrDefault(s => 
                string.Equals(s.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 根据ID获取AliCloudType
        /// </summary>
        /// <param name="id">AliCloudType ID</param>
        /// <returns>AliCloudType配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetAliCloudTypeById(int id)
        {
            if (!_isDataLoaded || _mqttConfigData?.AliCloudType == null)
            {
                return null;
            }
            
            return _mqttConfigData.AliCloudType.FirstOrDefault(a => a.Id == id);
        }

        /// <summary>
        /// 根据名称获取AliCloudType
        /// </summary>
        /// <param name="name">AliCloudType名称</param>
        /// <returns>AliCloudType配置项，如果不存在则返回null</returns>
        public static MqttConfigItem? GetAliCloudTypeByName(string name)
        {
            if (!_isDataLoaded || _mqttConfigData?.AliCloudType == null)
            {
                return null;
            }
            
            return _mqttConfigData.AliCloudType.FirstOrDefault(a => 
                string.Equals(a.Name, name, StringComparison.OrdinalIgnoreCase));
        }

        /// <summary>
        /// 清空数据
        /// </summary>
        public static void ClearData()
        {
            _mqttConfigData = null;
            _isDataLoaded = false;
            _configFilePath = string.Empty;
        }

        /// <summary>
        /// 重新加载数据
        /// </summary>
        /// <returns>是否重新加载成功</returns>
        public static bool ReloadData()
        {
            if (string.IsNullOrEmpty(_configFilePath))
            {
                return false;
            }
            
            return LoadFromJsonFile(_configFilePath);
        }

        /// <summary>
        /// 获取数据统计信息
        /// </summary>
        /// <returns>统计信息字符串</returns>
        public static string GetDataStatistics()
        {
            if (!_isDataLoaded || _mqttConfigData == null)
            {
                return "未加载数据";
            }
            
            var topicCount = _mqttConfigData.Topic?.Count ?? 0;
            var payloadCount = _mqttConfigData.Payload?.Count ?? 0;
            var networkCardCount = _mqttConfigData.NetworkCard?.Count ?? 0;
            var serverTypeCount = _mqttConfigData.ServerType?.Count ?? 0;
            var aliCloudTypeCount = _mqttConfigData.AliCloudType?.Count ?? 0;
            
            return $"已加载: Topic({topicCount}), Payload({payloadCount}), NetworkCard({networkCardCount}), ServerType({serverTypeCount}), AliCloudType({aliCloudTypeCount})";
        }

        /// <summary>
        /// 导出配置到JSON文件
        /// </summary>
        /// <param name="filePath">输出文件路径</param>
        /// <param name="configData">要导出的配置数据</param>
        public static void ExportToJsonFile(string filePath, MqttUIConfigData configData)
        {
            string jsonContent = Newtonsoft.Json.JsonConvert.SerializeObject(configData, Formatting.Indented);
            File.WriteAllText(filePath, jsonContent, new UTF8Encoding(false));
        }
    }
}
